package com.keba.lamp.complaint.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.keba.basic.base.R;
import com.keba.basic.base.controller.SuperController;
import com.keba.basic.base.request.PageParams;
import com.keba.basic.context.ContextUtil;
import com.keba.basic.database.mybatis.conditions.query.QueryWrap;
import com.keba.basic.interfaces.echo.EchoService;
import com.keba.basic.utils.BeanPlusUtil;
import com.keba.lamp.common.constant.BizConstant;
import com.keba.lamp.complaint.entity.EvidenceComponentCaseTypeRel;
import com.keba.lamp.complaint.manager.EvidenceComponentCaseTypeRelManager;
import com.keba.lamp.complaint.service.EvidenceComponentCaseTypeRelService;
import com.keba.lamp.complaint.service.EvidenceComponentService;
import com.keba.lamp.complaint.vo.query.EvidenceComponentCaseTypeRelPageQuery;
import com.keba.lamp.complaint.vo.result.EvidenceComponentCaseTypeRelResultVO;
import com.keba.lamp.complaint.vo.result.EvidenceComponentResultVO;
import com.keba.lamp.complaint.vo.save.EvidenceComponentCaseTypeRelSaveVO;
import com.keba.lamp.complaint.vo.update.EvidenceComponentCaseTypeRelUpdateVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * 案件类型和组件库关系表（证据目录）
 * </p>
 *
 * @author chaowu.wang
 * @date 2025-03-27 22:17:56
 * @create [2025-03-27 22:17:56] [chaowu.wang] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/evidenceComponentCaseTypeRel")
@Tag(name = "案件类型和组件库关系表（证据目录）")
public class EvidenceComponentCaseTypeRelController extends SuperController<EvidenceComponentCaseTypeRelService, Long, EvidenceComponentCaseTypeRel
    , EvidenceComponentCaseTypeRelSaveVO, EvidenceComponentCaseTypeRelUpdateVO, EvidenceComponentCaseTypeRelPageQuery, EvidenceComponentCaseTypeRelResultVO> {
    private final EchoService echoService;
    private final EvidenceComponentCaseTypeRelManager evidenceComponentCaseTypeRelManager;
    private final EvidenceComponentService evidenceComponentService;
    @Override
    public EchoService getEchoService() {
        return echoService;
    }

    @Override
    public QueryWrap<EvidenceComponentCaseTypeRel> handlerWrapper(EvidenceComponentCaseTypeRel model, PageParams<EvidenceComponentCaseTypeRelPageQuery> params) {
        QueryWrap<EvidenceComponentCaseTypeRel> wrap = super.handlerWrapper(model, params);
        Long tenantId = ContextUtil.getTenantId();
        if (!BizConstant.ADMIN_TENANT_ID.equals(tenantId)) {
            //租户取自己的证据目录+公共证据目录
            List<EvidenceComponentCaseTypeRel> tenantTypeRelList = evidenceComponentCaseTypeRelManager.listByTenantId(tenantId);
            if (CollectionUtil.isNotEmpty(tenantTypeRelList)) {
                Set<String> codeList = tenantTypeRelList.stream().map(EvidenceComponentCaseTypeRel::getCode).collect(Collectors.toSet());
                List<EvidenceComponentCaseTypeRel> adminTypeRelList = evidenceComponentCaseTypeRelManager.listByTenantId(BizConstant.ADMIN_TENANT_ID);
                Set<Long> adminIdSet = adminTypeRelList.stream().filter(e ->
                        codeList.contains(e.getCode())
                ).map(EvidenceComponentCaseTypeRel::getId).collect(Collectors.toSet());
                if (CollectionUtil.isNotEmpty(adminIdSet)) {
                    wrap.lambda().notIn(EvidenceComponentCaseTypeRel::getId, adminIdSet);
                }
            }
        }
        wrap.orderByDesc("updated_time");
        return wrap;
    }

    @Override
    public void handlerResult(IPage<EvidenceComponentCaseTypeRelResultVO> page) {
        super.handlerResult(page);
        fullAttr(page.getRecords());
    }

    /**
     * 补充返回属性信息
     * @param records
     */
    private void fullAttr(List<EvidenceComponentCaseTypeRelResultVO> records) {
        if (CollectionUtil.isNotEmpty(records)) {
            records.stream().filter(record ->
                    StringUtils.isNoneBlank(record.getComponentId())
            ).forEach(record -> {
                String componentIds = record.getComponentId();
                List<Long> componentIdList = Arrays.stream(componentIds.split(",")).map(Long::valueOf).collect(Collectors.toList());
                List<EvidenceComponentResultVO> componentResultVOList = evidenceComponentService.getComponentByIds(componentIdList);
                record.setComponentList(componentResultVOList);
            });
        }
    }

    @Override
    public R<List<EvidenceComponentCaseTypeRelResultVO>> query(EvidenceComponentCaseTypeRelPageQuery data) {
        R<List<EvidenceComponentCaseTypeRelResultVO>> list = super.query(data);
        fullAttr(list.getData());
        return list;
    }

    @Override
    public R<EvidenceComponentCaseTypeRelResultVO> getDetail(Long id) {
        EvidenceComponentCaseTypeRel entity = getSuperService().getById(id);
        EvidenceComponentCaseTypeRelResultVO resultVO = BeanPlusUtil.toBean(entity, getResultVOClass());
        fullAttr(Lists.newArrayList(resultVO));
        EchoService echoService = getEchoService();
        if (echoService != null) {
            echoService.action(resultVO);
        }
        return success(resultVO);
    }
}


